<template>
  <el-dialog
    v-el-drag-dialog
    title="设置角色权限"
    :visible.sync="visible"
    width="1024px"
    class="dialog"
    @closed="reset"
  >
    <el-table
      ref="tableRef"
      v-loading="$loadingPlugin.fetchData"
      class="permission-table"
      border
      row-key="menuId"
      default-expand-all
      element-loading-text="加载中"
      max-height="600"
      :data="tableData"
    >
      <el-table-column label="菜单权限" width="300">
        <template slot-scope="{ row }">
          <el-checkbox :value="row.selected" :indeterminate="row.isIndeterminate" @change="(val)=>checkChange(row, val)">{{ row.menuName }}</el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="默认数据权限" width="120">
        <template v-if="row.isDataScorp" slot-scope="{ row }">
          <i class="el-icon-success" />
        </template>
      </el-table-column>
      <el-table-column label="功能按钮">
        <template slot-scope="{ row }">
          <el-checkbox-group v-model="row.selectedBtnOptions">
            <el-checkbox v-for="item in row.btnOptions" :key="row.menuId + '_' + item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { moduleMenuQueryList, roleAuthorization } from '@/api'
  import getTreeData, { treeToArray } from '@/utils/jsonTree'

  export default {
    name: 'set-permission',
    data() {
      return {
        visible: false,
        role: null,
        tableData: []
      }
    },
    methods: {
      open(role) {
        this.visible = true
        this.role = role
        this.fetchData(role.id)
      },
      async fetchData() {
        const res = await moduleMenuQueryList({
          roleId: this.role.roleId,
          roleType: this.role.roleType
        })
        this.tableData = this._getTableData(getTreeData(res.data, 'parentId', 'menuId'))
        this.setTableDataIndeterminate()
      },
      _getTableData(treeData) {
        return treeData.map(item => {
          const rtn = {
            ...item,
            selectedBtnOptions: [],
            selected: false,
            isIndeterminate: false,
            selectedDataPer: false
          }
          rtn.selected = item.checked !== 0
          if (item.btnoptions) {
            rtn.btnOptions = this._getBtnOptions(item.btnoptions)
          }
          rtn.selectedBtnOptions = this._getSelectedBtnOptions(item.btnScope, rtn.btnOptions)
          if (rtn.children) {
            rtn.children = this._getTableData(item.children)
          }
          return rtn
        })
      },
      _getBtnOptions(str) {
        if (!str) return []
        return str.split(',').map(item => ({ id: item.split(':')[0], name: item.split(':')[1] }))
      },
      _getSelectedBtnOptions(btnScope, btnOptions) {
        if (btnOptions) {
          return btnOptions.filter(item => btnScope >> (item.id - 1) & 0x01).map(item => item.id)
        }
        return []
      },
      _getBtnScope(btnOptions, selectedBtnOptions) {
        let btnScope = 0
        if (btnOptions) {
          btnOptions.forEach(item => {
            const scope = item.id
            // 勾选
            if (selectedBtnOptions.find(it => it === item.id)) {
              btnScope |= 1 << (scope - 1)
            }
          })
        }
        return btnScope
      },
      checkChange(row) {
        const val = !row.selected
        row.selected = val
        if (row.children && row.children.length > 0) {
          if (row.isIndeterminate) {
            row.selected = true
            row.isIndeterminate = false
            row.children.forEach(item => item.selected = true)
          } else {
            row.children.forEach(item => item.selected = val)
          }
        }
        this.setTableDataIndeterminate()
        // this.checkBtn(row)
      },
      setTableDataIndeterminate(data) {
        if (!data) data = this.tableData
        data.forEach(item => {
          if (item.children) {
            this.setTableDataIndeterminate(item.children)
            if (item.children.every(item => item.selected)) {
              item.selected = true
              item.isIndeterminate = false
            } else if (item.children.every(item => !item.selected)) {
              item.selected = false
              item.isIndeterminate = false
            } else {
              item.isIndeterminate = true
              item.selected = true
            }
          }
        })
      },
      checkBtn(row) {
        if (row.selected) {
          if (row.btnOptions) row.selectedBtnOptions = row.btnOptions.map(item => item.id)
          if (row.children && row.children.length > 0) {
            row.children.forEach(item => this.checkBtn(item))
          }
        } else {
          row.selectedBtnOptions = []
          if (row.children) row.children.forEach(item => item.selectedBtnOptions = [])
        }
      },
      async success() {
        const menuList = treeToArray(this.tableData)
        const authorizationInfoList = []
        menuList.forEach(item => {
          if (item.selected) {
            const authorizationInfoItem = {
              menuId: item.menuId,
              btnScope: this._getBtnScope(item.btnOptions, item.selectedBtnOptions)
            }
            if (item.selectedDataPer) {
              authorizationInfoItem.moduleDataPerId = item.moduleDataPerId
            }
            authorizationInfoList.push(authorizationInfoItem)
          }
        })
        const query = {
          roleId: this.role.roleId,
          roleType: this.role.roleType,
          menuIds: authorizationInfoList.map(item => item.menuId).join(','),
          btnScopes: authorizationInfoList.map(item => item.btnScope).join(',')
        }
        await roleAuthorization(query)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '设置成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.role = null
        this.tableData = []
      }
    }
  }
</script>

<style lang="scss" scoped>
.dialog {
  & /deep/ .el-dialog__body {
    max-height: unset !important;
    padding: 0 !important;
  }
}
.permission-table {
  .el-checkbox {
    margin-right: 10px;
  }
  /deep/ .el-checkbox__label {
    padding-left: 3px;
  }
}
</style>
